import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {CommonTool} from '../../common/common.tool';
import {HTTP_URLS} from '../../config/app-http.url';
import {TableFindModel} from '../../common/table-find/table-find.model';
import {LoginDto} from '../../basic/basic.model';
import {environment} from '../../../environments/environment';
import {BUTTON_CODE} from '../../config/button-code';
import {CreateFolderComponent} from './create-folder/create-folder.component';

@Injectable({
  providedIn: 'root'
})
export class FileManagementService {

  constructor(private http: HttpClient) {

  }

  /**
   * 获取用户集合
   */
  public getMyAppUserList() {
    return this.http.get<any>(HTTP_URLS.getMyAppUserList);
  }

  /**
   * 创建目录
   */
  public createFolder(folderId, req: any): Observable<Array<any>> {
    const url = CommonTool.analysisParam(HTTP_URLS.createCurrentUserFolder, {folderId});
    return this.http.post<Array<any>>(url, req);
  }

  /**
   * 查询目录集合
   */
  public getUserFolderFile(req): Observable<Array<any>> {
    const url = CommonTool.analysisParam(HTTP_URLS.getCurrentUserFolderFile, req);
    return this.http.get<Array<any>>(url);
  }

  /**
   * 删除文件夹
   */
  public deleteFolder(folderId) {
    const url = CommonTool.analysisUrl(HTTP_URLS.deleteCurrentUserFolder, {folderId});
    return this.http.delete<any>(url);
  }

  /**
   * 删除文件夹
   */
  public deleteFile(fileId) {
    const url = CommonTool.analysisUrl(HTTP_URLS.deleteCurrentUserFile, {fileId});
    return this.http.delete<any>(url);
  }

  /**
   * 查询目录集合信息
   */
  public getUserFolderList(req) {
    const url = CommonTool.analysisParam(HTTP_URLS.getCurrentUserFolders, req);
    return this.http.get<any>(url);
  }

  /**
   * 移动目录
   */
  public updateUserFolderFile(req): Observable<any> {
    return this.http.put<any>(HTTP_URLS.updateCurrentUserFolderFile, req);
  }

  /**
   * 复制文件夹及文件
   */
  public createUserFolderFile(req) {
    return this.http.post<any>(HTTP_URLS.createCurrentUserFolderFile, req);
  }

  /**
   * 保存共享文件夹及文件
   */
  public createCurrentUserShareFolderFile(shareId, req) {
    const url = CommonTool.analysisParam(HTTP_URLS.createCurrentUserShareFolderFile, {shareId});
    return this.http.post<any>(url, req);
  }

  /**
   * 修改文件
   */
  public updateUserFile(id, req): Observable<any> {
    const url = CommonTool.analysisUrl(HTTP_URLS.updateCurrentUserFile, {fileId: id});
    return this.http.put<any>(url, req);
  }

  /**
   * 修改目录
   */
  public updateUserFolder(id, req): Observable<any> {
    const url = CommonTool.analysisUrl(HTTP_URLS.updateCurrentUserFolder, {folderId: id});
    return this.http.put<any>(url, req);
  }

  /**
   * 创建用户的文件包
   * 打包文件
   */
  public createUserFilePackage(req) {
    return this.http.post<any>(HTTP_URLS.createCurrentUserFolderFilePack, req);
  }

  /**
   * 分享文件
   */
  public createUserShare(req: { fileIds, folderIds, needCode; validTime, remark }): Observable<any> {
    return this.http.post<any>(HTTP_URLS.createCurrentUserShare, req);
  }

  /**
   * 查询共享文件
   *
   */
  public getUserSharePage(current, req): Observable<any> {
    let url = CommonTool.analysisUrl(HTTP_URLS.getCurrentUserSharePage, {current});
    url = CommonTool.analysisParam(url, req);
    return this.http.get(url);
  }

  /**
   * 删除共享文件
   */
  public deleteUserShare(shareId) {
    const url = CommonTool.analysisUrl(HTTP_URLS.deleteCurrentUserShare, {shareId});
    return this.http.delete<any>(url);
  }

  /**
   * 分页查询链接
   */
  public getUserSafetyChainPage(current, req) {
    let url = CommonTool.analysisUrl(HTTP_URLS.getCurrentUserSafetyChainPage, {current});
    url = CommonTool.analysisParam(url, req);
    return this.http.get<any>(url);
  }

  /**
   * 创建安全链接
   */
  public createUserSafetyChain(req) {
    return this.http.post<any>(HTTP_URLS.createCurrentUserSafetyChain, req);
  }

  /**
   * 更新安全链接
   */
  public updateUserSafetyChain(id, req) {
    const url = CommonTool.analysisUrl(HTTP_URLS.updateCurrentUserSafetyChain, {safetyChainId: id});
    return this.http.put<any>(url, req);
  }

  /**
   * 删除安全链接
   */
  public deleteUserSafetyChain(id) {
    const url = CommonTool.analysisUrl(HTTP_URLS.deleteCurrentUserSafetyChain, {safetyChainId: id});
    return this.http.delete<any>(url);
  }

  /**
   * 查询共享文件
   */
  public getShareFolderFile(req) {
    const url = CommonTool.analysisParam(HTTP_URLS.getShareFolderFile, req);
    return this.http.get<any>(url);
  }

  /**
   * 获取系统文件集合
   */
  public verifyShareCode(code, drawCode?) {
    let url = CommonTool.analysisUrl(HTTP_URLS.verifyShareCode, {code});
    url = CommonTool.analysisParam(url, {drawCode});
    return this.http.get<any>(url);
  }

  /**
   * 获取系统文件集合
   */
  public getUploadUrl() {
    return HTTP_URLS.uploadFile;
  }

  /**
   * 获取文件夹大小
   */
  public getUserFolderSize(folderId) {
    const url = CommonTool.analysisUrl(HTTP_URLS.getCurrentUserFolderSize, {folderId});
    return this.http.get<any>(url);
  }

  /**
   * 获取父级文件夹集合
   */
  public getParentFolderList(folderId) {
    const url = CommonTool.analysisParam(HTTP_URLS.getParentFolderList, {folderId});
    return this.http.get<any>(url);
  }


  /**
   * 获取共享文件夹大小
   */
  public getShareFolderSize(shareId, folderId) {
    const url = CommonTool.analysisUrl(HTTP_URLS.getShareFolderSize, {shareId, folderId});
    return this.http.get<any>(url);
  }

  /**
   * 获取共享父级文件夹集合
   */
  public getShareParentFolderList(shareId, folderId) {
    let url = CommonTool.analysisUrl(HTTP_URLS.getShareParentFolderList, {shareId});
    url = CommonTool.analysisParam(url, {folderId});
    return this.http.get<any>(url);
  }

  /**
   * 创建当前用户的cdn地址
   */
  public createCdnUrl(fileId) {
    const url = CommonTool.analysisUrl(HTTP_URLS.createCdnUrl, {fileId});
    return this.http.post<any>(url, {});
  }

  /**
   * 获取当前用户网盘信息
   */
  public getUserDiskInfo() {
    return this.http.get<any>(HTTP_URLS.getUserDiskInfo);
  }

  /**
   * 获取文件夹数组
   *
   * folderPath 文件夹字符串路径
   * 文件夹数据
   */
  public getFolderPaths(folderPath) {
    let folderPaths = [];
    if (folderPath) {
      if ('/' === folderPath.substring(0, 1)) {
        folderPath = folderPath.substring(1);
      }
      folderPaths = folderPath.split('/');
    }
    return folderPaths;
  }

  /**
   * 验证后缀是否是图片
   * 图片名称 name
   */
  public verifyImageSuffix(suffix) {
    return suffix === '.jpg' || suffix === '.png' || suffix === '.jpeg' || suffix === 'gif' || suffix === 'bmp';
  }

  /**
   * 初始化选择数据
   */
  public selectFolder(imgConfig, createFolderComponent: CreateFolderComponent, fun, config: { isMyOf, userList? }) {
    const tableFindModel = new TableFindModel();
    const COMMON_TYPE = TableFindModel.COMMON_TYPE;
    const myThis = this;
    let path = '';
    const labels = [{name: '全部', folderId: ''}];
    tableFindModel.initAll({
      finds: [
        {
          name: '文件夹名',
          field: 'name',
          input: {
            maxLength: 255
          }
        }
      ],
      tables: [
        {
          name: '', field: 'imageUrl', type: COMMON_TYPE.table.IMAGE,
          tdStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            path = path + '/' + dataModel.data.name;
            const label = {name: dataModel.data.name, folderId: dataModel.data.id, path};
            labels.push(label);
            fun(label);
            that.getData({folderId: dataModel.data.id}, null);
          }
        },
        {
          name: '文件夹名',
          field: 'name',
          type: COMMON_TYPE.table.TITLE,
          isSort: true,
          tdStyle: {cursor: 'pointer'},
          confirmFun: (dataModel, table, that) => {
            path = path + '/' + dataModel.data.name;
            const label = {name: dataModel.data.name, folderId: dataModel.data.id, path};
            labels.push(label);
            fun(label);
            that.getData({folderId: dataModel.data.id}, null);
          }
        },
        {
          name: '', field: 'createTime', type: COMMON_TYPE.table.DESCRIPTION,
          confirmFun: (dataModel, table, that) => {
            path = path + '/' + dataModel.data.name;
            const label = {name: dataModel.data.name, folderId: dataModel.data.id, path};
            labels.push(label);
            fun(label);
            that.getData({folderId: dataModel.data.id}, null);
          }
        }
      ],
      buttons: [
        {
          name: '创建目录',
          type: COMMON_TYPE.button.BUTTON,
          bAuthority: BUTTON_CODE.b_folder_add,
          confirmFun: (formInfo) => {
            createFolderComponent.create(formInfo['folderId']);
          }
        }
      ],
      breadcrumb: {
        breadcrumbFun: (label, i, that) => {
          if (i + 1 < labels.length) {
            labels.splice(i + 1, labels.length);
          }
          fun(labels[i]);
          that.getData({folderId: labels[i].folderId}, null);
        },
        labels: [] // 面包屑
      },
      initDataFun(formInfo, sortPage, callback, that) {// 数据处理回调 config：配置，dataModels：数据，that：当前对象
        const req = {
          sortField: sortPage.sortField,
          sortRule: sortPage.sortRule,
          likeFields: ['name'],
          folderId: formInfo['folderId']
        };
        for (const find of that.config.finds) {
          req[find.field] = formInfo[find.field];
        }
        if (config.isMyOf) {
          const tokenInfo = new LoginDto(JSON.parse(CommonTool.getCookie(environment.tokenKey)));
          req['userId'] = tokenInfo.userId;
        }
        myThis.getUserFolderList(req).subscribe(res => {
          const array = [];
          let userId = null;
          const tokenInfo = new LoginDto(JSON.parse(CommonTool.getCookie(environment.tokenKey)));
          for (const arr of res) {
            if (!config.isMyOf) {
              if (arr.userId === tokenInfo.userId) {
                arr.createTime = '我的 | ' + arr.createTime;
              }
              for (const user of config.userList) {
                if (user.userId === arr.userId && tokenInfo.userId !== user.userId) {
                  arr.createTime = user.nickName + ' | ' + arr.createTime;
                }
              }
            }
            userId = arr.userId;
            arr['imageUrl'] = imgConfig['disk_icon_folder'];
            array.push({data: arr, isFile: false});
          }
          that.config.breadcrumb.labels = labels;
          callback(array, {size: array.length});
        });
      },
      openPaging: false,
      frontSort: false,
      openButton: true
    }, null, {folderId: ''});
    return tableFindModel;
  }
}
